package com.swq.java.code.chapter13.code14;

public class Machine extends Thread {
    private int a;
    private static int count;

    public void start() {
        super.start();
        Thread deamon = new Thread() {  //匿名线程类
            public void run() {
                while (true) {  //无限循环
                    //每隔1秒把实例变量a设为0。
                    reset();
                    try {
                        sleep(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        deamon.setDaemon(true);
        deamon.start();
    }

    public void reset() {
        a = 0;
    }

    @Override
    public void run() {
        while (true) {
            // 调用sleep方法更能看出后台线程的作用
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(getName() + ":" + a++);
            if (count++ == 100) break;
            yield();
        }
    }

    public static void main(String args[]) throws Exception {
        Machine machine = new Machine();
        machine.start();
    }
}
